package com.system.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jmnarloch.spring.cloud.ribbon.support.RibbonFilterContextHolder;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

/**
 * @author lisiyu
 * @create 2022-10-21 21:10
 * @version1.0
 */
@Component
public class MyPreFilter1 extends ZuulFilter {
    //声明过滤器的类型：前置 后置 错误
    @Override
    public String filterType() {
        //相当于return "pre"
        return FilterConstants.PRE_TYPE;
    }
    //顺序 排序 过滤器的顺序，数字越小，优先级越高
    //仅限于相同类型的过滤器
    @Override
    public int filterOrder() {
        //前置过滤器优先级要比系统内置的过滤器加1，防止空指针
        return FilterConstants.PRE_DECORATION_FILTER_ORDER+1;
    }
    //是否启用当前过滤器
    @Override
    public boolean shouldFilter() {
        return true;
    }
    //过滤器要执行的代码
    @Override
    public Object run() throws ZuulException {
        System.out.println("run方法执行了");
        //前置过滤器可以干什么，可以获取到请求对象，可以获取响应对象
        //可以拦截请求，返回其他数据
        //获取请求和响应对象
        //获取到请求的上下文对象
        RequestContext requestContext = RequestContext.getCurrentContext();
       /* HttpServletRequest request = requestContext.getRequest();
        HttpServletResponse response = requestContext.getResponse();
*/
        //拦截请求
        //requestContext.setSendZuulResponse(false);
        //返回数据
//        HttpServletResponse response = requestContext.getResponse();
//        try {
//            response.getWriter().write("yemianbeilanjiele");
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
        //设置响应正文，不管有没有拦截，都会返回这个数据
        //requestContext.setResponseBody("haohaoxuexiba");
        requestContext.set("name","lisiyu");
        //强制转发服务
//        requestContext.set(FilterConstants.SERVICE_ID_KEY,"addressprovidereureka04");
//        requestContext.set(FilterConstants.REQUEST_URI_KEY,"/address/info/12");
        //location来确定用户的位置
        String location = requestContext.getRequest().getParameter("location");
        if ("changzhi".equals(location)){
            //转发到为1的用户
            RibbonFilterContextHolder.getCurrentContext().add("forward","1");

        }else {
            //转发到为1的用户
            RibbonFilterContextHolder.getCurrentContext().add("forward","2");

        }
        return null;
    }
}
